package com.learn.core.controller.learn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.http.OkHttps;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.CourseEnroll;
import com.learn.core.domain.view.ExamTarget;
import com.learn.core.domain.view.ExamUser;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.LCourseDTO;
import com.learn.core.dto.LExamDTO;
import com.learn.core.dto.LExamSortDTO;
import com.learn.core.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName MyExamController
 * @date 2021.04.01 08:31
 * @describe 我的考试
 */
@Api("我的考试")
@RestController
@RequestMapping("/learn/myexam")
public class MyExamController {
    @Autowired
    private ILExamService ilExamService;
    @Autowired
    private ILExamUserService ilExamUserService;
    @Autowired
    private IExamTargetService iExamTargetService;
    @Autowired
    private ILExamPaperService ilExamPaperService;
    @Autowired
    private IExamUserService iExamUserService;
    @Autowired
    private ILExamSortService ilExamSortService;
    @Autowired
    private ILUserService ilUserService;
    @Autowired
    private ILQuestionsService ilQuestionsService;
    @Autowired
    private ILOptionService ilOptionService;
    @Autowired
    private ILUserAnswerService ilUserAnswerService;
    @Autowired
    private ILExtractQuestionsService ilExtractQuestionsService;
    @Autowired
    private ILOrganizationService ilOrganizationService;
    @Autowired
    private IUserDetailsGatherService iUserDetailsGatherService;
    @Autowired
    private ILGroupingUserService ilGroupingUserService;


    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //我的考试列表
    @ApiOperation(value = "我的考试列表")
    @UserLoginToken
    @PostMapping("/examList")
    public PageResult<ExamUser> examList(@RequestBody LExamDTO lExamDTO, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lExamDTO==null||lExamDTO.getPage()==null||lExamDTO.getRows()==null){
                return new PageResult<ExamUser>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lExamDTO.getPage(),lExamDTO.getRows());
            QueryWrapper<ExamUser> queryWrapper = new QueryWrapper<ExamUser>();
            if(StringUtils.isNotEmpty(lExamDTO.getExamSortId()))
                queryWrapper.eq("exam_sort_id",lExamDTO.getExamSortId());
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("release_state","1");
            if("0".equals(lExamDTO.getState()))
                queryWrapper.ne("exam_user_state","2");
            else
                queryWrapper.eq("exam_user_state","2");
            if(StringUtils.isNotEmpty(lExamDTO.getType()))
                queryWrapper.eq("type",lExamDTO.getType());
            queryWrapper.gt("failure_time",formatter.format(new Date()));
            queryWrapper.orderByDesc("release_time");
            Page<ExamUser> lExams = (Page<ExamUser>) iExamUserService.list(queryWrapper);
            for (ExamUser examUser: lExams) {
                LOrganization lOrganization = ilOrganizationService.getById(examUser.getOrganizationId());
                if(null != lOrganization)
                    examUser.setOrganizationName(lOrganization.getOrganizationName());
                QueryWrapper countWrapper = new QueryWrapper<LExamUser>();
                countWrapper.eq("user_id",userId);
                countWrapper.eq("exam_id",examUser.getExamId());
                countWrapper.eq("exam_user_state","2");
                int count = ilExamUserService.count(countWrapper);
                examUser.setCount(count);
                countWrapper = new QueryWrapper<LExamUser>();
                countWrapper.eq("user_id",userId);
                countWrapper.eq("exam_id",examUser.getExamId());
                countWrapper.ne("exam_user_state","2");
                int countType = ilExamUserService.count(countWrapper);
                examUser.setCountType(countType);
            }
            // 返回
            return new PageResult(lExams.getTotal(), lExams, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //考试分类列表
    @ApiOperation(value = "考试分类列表")
    @UserLoginToken
    @PostMapping("/examSortlist")
    public PageResult<LExamSort> examSortlist(@RequestBody LExamSortDTO lExamSortDTO){
        try {
            if (lExamSortDTO==null||lExamSortDTO.getPage()==null||lExamSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lExamSortDTO.getPage(),lExamSortDTO.getRows());
            QueryWrapper<LExamSort> queryWrapper = new QueryWrapper<LExamSort>();
            if(lExamSortDTO.getParentNode()!=null)
                queryWrapper.eq("parent_node",lExamSortDTO.getParentNode());
            Page<LExamSort> lExamSorts = (Page<LExamSort>) ilExamSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lExamSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LExamSort lExamSort: lExamSorts) {
                LOrganization lOrganization = ilOrganizationService.getById(lExamSort.getOrganizationId());
                if(null != lOrganization)
                    lExamSort.setOrganizationName(lOrganization.getOrganizationName());
            }
            // 返回
            return new PageResult(lExamSorts.getTotal(), lExamSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //考试详情
    @ApiOperation(value = "考试详情")
    @UserLoginToken
    @GetMapping("/examInfo")
    public CommonResult<Object> examInfo(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            LExamUser lExamUser = ilExamUserService.getById(id);

            Map<String,Object> map = new HashMap<>();
            LUser lUser = ilUserService.getById(lExamUser.getUserId());
            map.put("user",lUser);
            map.put("examUserId",id);
            QueryWrapper queryWrapper = new QueryWrapper<LExamUser>();
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("exam_user_state","2");
            int count = ilExamUserService.count(queryWrapper);
            map.put("count",count);
            LExam lExam = ilExamService.getById(lExamUser.getExamId());
            map.put("exam",lExam);
            Map<String,Object> questionMap = new HashMap<>();
            LExamPaper lExamPaper = ilExamPaperService.getById(lExamUser.getExamPaperId());
            if(null != lExamPaper){
                String question = lExamPaper.getExamQuestionsId();
                JSONObject json = JSONObject.fromObject(question);
                if(StringUtils.isNotEmpty(json.get("check"))){
                    List<Integer> list = (List) json.get("check");
                    List<LQuestions> lQuestionsList = new ArrayList<>();
                    for (Integer integer : list) {
                        LQuestions lQuestions = ilQuestionsService.getById(integer);
                        if(null != lQuestions){
                            QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                            queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                            List<LOption> lOptionList = ilOptionService.list(queryLOption);
                            lQuestions.setlOptionList(lOptionList);
                            lQuestions.setExamineAnswer(new ArrayList());
                        }
                        lQuestionsList.add(lQuestions);
                    }
                    questionMap.put("check",lQuestionsList);
                }
                if(StringUtils.isNotEmpty(json.get("judge"))){
                    List<Integer> list = (List) json.get("judge");
                    List<LQuestions> lQuestionsList = new ArrayList<>();
                    for (Integer integer : list) {
                        LQuestions lQuestions = ilQuestionsService.getById(integer);
                        if(null != lQuestions){
                            QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                            queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                            List<LOption> lOptionList = ilOptionService.list(queryLOption);
                            lQuestions.setlOptionList(lOptionList);
                            lQuestions.setExamineAnswer(new ArrayList());
                        }
                        lQuestionsList.add(lQuestions);
                    }
                    questionMap.put("judge",lQuestionsList);
                }
                if(StringUtils.isNotEmpty(json.get("radio"))){
                    List<Integer> list = (List) json.get("radio");
                    List<LQuestions> lQuestionsList = new ArrayList<>();
                    for (Integer integer : list) {
                        LQuestions lQuestions = ilQuestionsService.getById(integer);
                        if(null != lQuestions){
                            QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                            queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                            List<LOption> lOptionList = ilOptionService.list(queryLOption);
                            lQuestions.setlOptionList(lOptionList);
                            lQuestions.setExamineAnswer(new ArrayList());
                        }
                        lQuestionsList.add(lQuestions);
                    }
                    questionMap.put("radio",lQuestionsList);
                }
            }
            map.put("examQuestions",questionMap);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //个人答题情况
    @ApiOperation(value = "个人答题情况")
    @UserLoginToken
    @GetMapping("/userAnswer")
    public CommonResult<Object> userAnswer(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            LExamUser lExamUser = ilExamUserService.getById(id);
            QueryWrapper<LUserAnswer> lUserAnswerQueryWrapper = new QueryWrapper<LUserAnswer>();
            lUserAnswerQueryWrapper.eq("exam_user_id",lExamUser.getExamUserId());
            List<LUserAnswer> lUserAnswerList = ilUserAnswerService.list(lUserAnswerQueryWrapper);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lUserAnswerList);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //答题
    @ApiOperation(value = "答题")
    @UserLoginToken
    @PostMapping("/saveAnswer")
    public CommonResult<Object> saveAnswer(@RequestBody LUserAnswer lUserAnswer){
        try {
            if(ilUserAnswerService.save(lUserAnswer))
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //提交试卷
    @ApiOperation(value = "提交试卷")
    @UserLoginToken
    @GetMapping("/save")
    public CommonResult<Object> save(@RequestParam("examUserId")Integer examUserId,@RequestParam("examTime")String examTime,
                                     HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 报名记录
            LExamUser lExamUser = ilExamUserService.getById(examUserId);
            // 考次
            LExam lExam = ilExamService.getById(lExamUser.getExamId());
            // 考试记录
            QueryWrapper<LUserAnswer> lUserAnswerQueryWrapper = new QueryWrapper<LUserAnswer>();
            lUserAnswerQueryWrapper.eq("exam_user_id",lExamUser.getExamUserId());
            List<LUserAnswer> lUserAnswers = ilUserAnswerService.list(lUserAnswerQueryWrapper);
            int scores = 0;
            for (LUserAnswer lUserAnswer : lUserAnswers) {
                LQuestions lQuestions = ilQuestionsService.getById(lUserAnswer.getQuestionsId());
                String [] answer = lQuestions.getQuestionsAnswer().split(",");
                String [] userAnswer =lUserAnswer.getUserAnswer().split(",");
                if(StringUtils.equalsIgnoreOrder(answer,userAnswer)){
                    if("1".equals(lExam.getFractionType())){
                        scores += lQuestions.getQuestionsFraction();
                    }else{
                        QueryWrapper<LExtractQuestions> lExamUserQueryWrapper = new QueryWrapper<LExtractQuestions>();
                        lExamUserQueryWrapper.eq("exam_id",lExamUser.getExamId());
                        lExamUserQueryWrapper.eq("questions_type_id",lQuestions.getQuestionsType());
                        LExtractQuestions lExtractQuestions = ilExtractQuestionsService.getOne(lExamUserQueryWrapper);
                        scores += Integer.parseInt(lExtractQuestions.getQuestionsFraction());
                    }
                }
            }
            LExamUser examUser = new LExamUser();
            examUser.setExamUserId(lExamUser.getExamUserId());

            examUser.setExamUserState("2");
            examUser.setExamTime(new Date());
            examUser.setExamUserTime(examTime);
            examUser.setUserScore(scores);
            if(ilExamUserService.updateById(examUser))
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,examUser);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //我的考试结果
    @ApiOperation(value = "我的考试结果")
    @UserLoginToken
    @PostMapping("/myExamlist")
    public PageResult<LExamSort> myExamlist(@RequestBody LExamSortDTO lExamSortDTO,HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (lExamSortDTO==null||lExamSortDTO.getPage()==null||lExamSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lExamSortDTO.getPage(),lExamSortDTO.getRows());
            QueryWrapper<ExamUser> lExamUserQueryWrapper = new QueryWrapper<>();
            lExamUserQueryWrapper.eq("user_id",userId);
            lExamUserQueryWrapper.eq("type","1");
            Page<ExamUser> lExamUserList = (Page<ExamUser>) iExamUserService.list(lExamUserQueryWrapper);
            if (CollectionUtils.isEmpty(lExamUserList)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (ExamUser lExamUser : lExamUserList) {
                QueryWrapper<UserDetailsGather> gatherQueryWrapper = new QueryWrapper<UserDetailsGather>();
                gatherQueryWrapper.eq("user_id" ,lExamUser.getUserId());
                UserDetailsGather lUser = iUserDetailsGatherService.getOne(gatherQueryWrapper);
                if(null != lUser)
                    lExamUser.setUserName(lUser.getName());
            }
            // 返回
            return new PageResult(lExamUserList.getTotal(), lExamUserList, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //习题列表
    @ApiOperation(value = "习题列表")
    @UserLoginToken
    @PostMapping("/progressExam")
    public CommonResult<Object> progressExam(HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 用户信息
            UserDetailsGather userDetailsGather = userInfo(userId);
            // 用户分组
            List userGroup = userGroup(userId);

            Date date = new Date();
            String startTime = formatter.format(date);
            String endTime = formatter.format(date);
            QueryWrapper<ExamTarget> queryWrapper = new QueryWrapper<ExamTarget>();
            queryWrapper.eq("release_state","1");
            queryWrapper.eq("type","2");
            queryWrapper.apply(" ((timing_type != '2' AND failure_time > '"+startTime +"') " +
                    "or (timing_type = '2' AND timing_start_time <= '"+startTime +"' AND timing_end_time >= '"+endTime +"'))");
            if(userGroup.size() > 0){
                queryWrapper.and(i -> i.eq("exam_target_type","0").eq("exam_target", userDetailsGather.getOrganizationId())
                        .or(a -> a.eq("exam_target_type", "1").in("exam_target", userGroup)));
            }else{
                queryWrapper.and(i -> i.eq("exam_target_type","0").eq("exam_target", userDetailsGather.getOrganizationId()));
            }
            queryWrapper.orderByAsc("release_time");
            List<ExamTarget> list = iExamTargetService.list(queryWrapper);
            for (ExamTarget examTarget : list) {
                QueryWrapper<LExamUser> lExamUserQueryWrapper = new QueryWrapper<LExamUser>();
                lExamUserQueryWrapper.eq("exam_id",examTarget.getExamId());
                lExamUserQueryWrapper.eq("user_id",userId);
                LExamUser lExamUser = ilExamUserService.getOne(lExamUserQueryWrapper);
                if(null != lExamUser){
                    examTarget.setUserExam("1");
                }else{
                    examTarget.setUserExam("0");
                }
                LOrganization lOrganization = ilOrganizationService.getById(examTarget.getOrganizationId());
                if(null != lOrganization)
                    examTarget.setOrganizationName(lOrganization.getOrganizationName());
                LExamSort lExamSort = ilExamSortService.getById(examTarget.getExamSortId());
                if(null != lExamSort)
                    examTarget.setExamSortName(lExamSort.getExamSortName());
                QueryWrapper countWrapper = new QueryWrapper<LExamUser>();
                countWrapper.eq("user_id",userId);
                countWrapper.eq("exam_id",examTarget.getExamId());
                countWrapper.eq("exam_user_state","2");
                int count = ilExamUserService.count(countWrapper);
                examTarget.setCount(count);
                countWrapper = new QueryWrapper<LExamUser>();
                countWrapper.eq("user_id",userId);
                countWrapper.eq("exam_id",examTarget.getExamId());
                countWrapper.ne("exam_user_state","2");
                int counttype = ilExamUserService.count(countWrapper);
                examTarget.setCountType(counttype);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //报名考试
    @ApiOperation(value = "报名考试")
    @UserLoginToken
    @PostMapping("/enrollExam")
    public CommonResult<Object> enrollExam(@RequestBody LExamUser lExamUser, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(null != lExamUser){
                if(StringUtils.isEmpty(lExamUser.getExamId()))
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM);
                QueryWrapper<LExamPaper> queryWrapper = new QueryWrapper<LExamPaper>();
                queryWrapper.eq("exam_id",lExamUser.getExamId());
                queryWrapper.last("order by rand() LIMIT 1");
                LExamPaper lExamPaper = ilExamPaperService.getOne(queryWrapper);
                if(null != lExamPaper)
                    lExamUser.setExamPaperId(lExamPaper.getExamPaperId());
                lExamUser.setUserIp(OkHttps.getIpAddr(request));
                lExamUser.setUserId(Integer.parseInt(userId));
                lExamUser.setCreateTime(new Date());
                lExamUser.setExamUserState("0");
                if(ilExamUserService.save(lExamUser))
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lExamUser.getExamUserId());
            }
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //答题情况
    @ApiOperation(value = "答题情况")
    @UserLoginToken
    @GetMapping("/answer")
    public CommonResult<Object> answer(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            LExamUser lExamUser = ilExamUserService.getById(id);
            QueryWrapper<LUserAnswer> lUserAnswerQueryWrapper = new QueryWrapper<LUserAnswer>();
            lUserAnswerQueryWrapper.eq("exam_user_id",lExamUser.getExamUserId());
            List<LUserAnswer> lUserAnswerList = ilUserAnswerService.list(lUserAnswerQueryWrapper);
            for (LUserAnswer lUserAnswer: lUserAnswerList) {
                LQuestions lQuestions = ilQuestionsService.getById(lUserAnswer.getQuestionsId());
                if(null != lQuestions) {
                    lUserAnswer.setQuestionsAnswer(lQuestions.getQuestionsAnswer());
                    lUserAnswer.setQuestionsExplain(lQuestions.getQuestionsExplain());
                    if (lQuestions.getQuestionsAnswer().equals(lUserAnswer.getUserAnswer()))
                        lUserAnswer.setAnswerType("1");
                    else
                        lUserAnswer.setAnswerType("2");
                }else
                    lUserAnswer.setAnswerType("2");
            }

            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lUserAnswerList);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    // 用户详情
    private UserDetailsGather userInfo(String userId){
        QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<UserDetailsGather>();
        userDetailsGatherQueryWrapper.eq("user_id",userId);
        UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);
        return userDetailsGather;
    }

    // 用户分组
    private List userGroup(String userId){
        List groupId = new ArrayList();
        QueryWrapper<LGroupingUser> lGroupingUserQueryWrapper = new QueryWrapper<LGroupingUser>();
        lGroupingUserQueryWrapper.eq("user_id",userId);
        List<LGroupingUser> lGroupingUsers = ilGroupingUserService.list(lGroupingUserQueryWrapper);
        for (LGroupingUser lGroupingUser : lGroupingUsers) {
            groupId.add(lGroupingUser.getGroupingId());
        }
        return groupId;
    }
}
